package util

import (
	"context"
	"fmt"
	"gowork/goKit/consulClientKit/service"
	"io"
	"net/url"
	"os"
	"time"

	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
	"github.com/go-kit/kit/sd/consul"
	"github.com/go-kit/kit/sd/lb"
	httpTransport "github.com/go-kit/kit/transport/http"
	"github.com/hashicorp/consul/api"
)

func GetUtil() (string, error){
	config := api.DefaultConfig()
	config.Address = "127.0.0.1:8500"

	apiClient, cErr := api.NewClient(config)
	if cErr != nil{
		fmt.Println(cErr)
		return "", cErr
	}

	client := consul.NewClient(apiClient)

	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stdout)
	}

	tags := []string{"primary"}
	instancer := consul.NewInstancer(client, logger, "userservice", tags, true)

	factory := func(serviceUrl string)(endpoint.Endpoint, io.Closer, error){
		tart, _ := url.Parse("http://" + serviceUrl)
		return httpTransport.NewClient("GET", tart, service.GetUserRequest, service.PutUserResponse).Endpoint(), nil, nil
	}

	endpointer:= sd.NewEndpointer(instancer, factory, logger)
	endpoints, eErr := endpointer.Endpoints()
	if eErr != nil{
		fmt.Println(eErr)
		return "", eErr
	}
	fmt.Println(endpoints, len(endpoints))

	//负载均衡
	//myLb := lb.NewRoundRobin(endpointer)
	myLb := lb.NewRandom(endpointer, time.Now().UnixNano())
	for{
		//userInfo := endpoints[0]
		userInfo, uErr := myLb.Endpoint()
		if uErr != nil{
			fmt.Println(uErr)
			//return "", uErr
		}
		ctx := context.Background()
		res, err := userInfo(ctx, service.UserRequest{Uid: 101})
		if err != nil{
			fmt.Println(err)
			//return "", err
		}
		//fmt.Println(res.(service.UserResponse).Result)
		fmt.Println(res)
		//return res.(service.UserResponse).Result, nil
		//time.Sleep(time.Second*3)
	}
}